﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace Brain.Ballistics3D
{
    public class Weapon : IUpdateable
    {
        public bool ShouldUpdate { get; set; }

        public WeaponInfo Info { get; set; }

        public SetBullet3D OnHit;

        protected BulletManager3D BulletManager;

        public object Tag;

        public IWorldObject WorldObject;

        public Weapon(BulletManager3D manager, WeaponInfo info)
        {
            this.BulletManager = manager;
            this.Info = info;
            ShouldUpdate = true;

            this.OnHit = OnBulletHit;
        }

        public virtual bool Shoot(int X, int Y, ICamera3D Camera, Vector3 Position)
        {
            if (weaponTimer >= Info.TimeBetweenShots)
            {
                weaponTimer = 0;

                // SHOOT
                if (Info.IsMelee)
                {
                    return true;
                }
                else
                {
                    Viewport Viewport = Engine.Instance.GraphicsDevice.Viewport;

                    Vector3 CloseShot = Viewport.Unproject(new Vector3(X, Y, 0), Camera.Projection,
                        Camera.View, Matrix.Identity);
                    Vector3 FarShot = Viewport.Unproject(new Vector3(X, Y, 1), Camera.Projection,
                        Camera.View, Matrix.Identity);
                    Vector3 Direction = FarShot - CloseShot;
                    if (Direction != Vector3.Zero)
                    {
                        Direction.Normalize();
                    }

                    BulletManager.AddBullet(Position, Direction, this.Info, OnHit);
                    return true;
                }
            }
            return false;
        }

        public virtual void OnBulletHit(Bullet3D bullet)
        {
        }

        protected int weaponTimer;
        public virtual void Update()
        {
            if (weaponTimer <= Info.TimeBetweenShots)
            {
                weaponTimer += Engine.Instance.GameTime.ElapsedGameTime.Milliseconds;
            }
        }

    }
}
